/*
 * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package com.dc.gameserver.extComponents.Kit.page;

import java.util.List;

public class SimplePageable<T> implements Pageable<T> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2806556524872482465L;

//	private static final int MAX_RESULT_SIZE = 1000;

	/** 当前页数据 */
	private List<T> elements;

	/** 每页数据条数 */
	private int pageSize;

	/** 第几页 */
	private int pageIndex;

	/** 记录总数 */
	private long recordCount = 0;

	/** 是否有下一页 */
	private final boolean hasNext;

	/** 是否有上一页 */
	private final boolean hasPrevious;

	/** 总页数 */
	private int pageCount;

	/**
	 * 构建SimplePaginaction对象
	 * 
	 * @param elements    elements列表
	 *
	 * @param pi
	 *            当前页编码，从1开始，如果传的值为Integer.MAX_VALUE表示获取最后一页。
	 *            如果你不知道最后一页编码，传Integer.MAX_VALUE即可。如果当前页超过总页数，也表示最后一页。
	 *            这两种情况将重新更改当前页的页码，为最后一页编码。
	 * @param ps
	 *            每一页显示的条目数，当pageSize<=0时，表示取所有记录
	 * @param total
	 *            总数
	 * @throws DBException
	 */
	public SimplePageable(final List<T> elements, final long recordCount,
			final int pageSize, final int pageIndex) {
		if (pageSize <= 0) {
			throw new IllegalArgumentException("Page Size <= 0");
		}
		
		this.pageIndex = pageIndex;
		this.pageSize = pageSize;
		this.recordCount = recordCount;
		this.elements = elements;

		if (this.pageIndex < 1) {
			this.pageIndex = 1;
		}
		
		if (this.recordCount < 0) {
			this.recordCount = 0;
		}

		pageCount = (int) ((this.recordCount % this.pageSize == 0) ? (this.recordCount / this.pageSize)
				: (this.recordCount / this.pageSize) + 1);

		if ((Integer.MAX_VALUE == this.pageIndex)
				|| (this.pageIndex > pageCount)) {
			this.pageIndex = pageCount;
		}
		if (this.pageIndex < 1) {
			this.pageIndex = 1;
		}

		this.hasNext = this.pageIndex < pageCount;
		this.hasPrevious = this.pageIndex > 1;
	}

	@Override
	public List<T> getElements() {
		return this.elements;
	}

	@Override
	public int getPageCount() {
		return this.pageCount;
	}

	@Override
	public int getPageIndex() {
		return this.pageIndex;
	}

	@Override
	public int getPageSize() {
		return this.pageSize;
	}

	@Override
	public long getRecordCount() {
		return this.recordCount;
	}

	@Override
	public boolean isHasNext() {
		return this.hasNext;
	}

	@Override
	public boolean isHasPrevious() {
		return this.hasPrevious;
	}

	@Override
	public long getPageFirstElementIndex() {
		return (getPageIndex() - 1) * this.pageSize + 1;
	}

	@Override
	public long getPageLastElementIndex() {
		final long fullPage = getPageFirstElementIndex() + this.pageSize - 1;
		return getRecordCount() < fullPage ? getRecordCount() : fullPage;
	}
}
